package com.item.task;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.base.task.ScheduleJob;
import com.base.util.DateUtil;
import com.base.util.SpringContextUtil;
import com.item.dao.model.EssenceExample;
import com.item.dao.model.EssenceNew;
import com.item.dao.model.EssenceNewExample;
import com.item.dao.model.News;
import com.item.dao.model.NewsExample;
import com.item.dao.model.Note;
import com.item.dao.model.NoteExample;
import com.item.dao.model.Unread;
import com.item.dao.model.UnreadExample;
import com.item.service.EssenceAuthorService;
import com.item.service.EssenceNewService;
import com.item.service.EssenceService;
import com.item.service.NewsService;
import com.item.service.NoteService;
import com.item.service.UnreadService;
import com.item.util.MyDateUtils;
import com.item.util.MyExcelUtils;
import com.item.util.SubjectUtils;

/**
 * 定时任务运行工厂类
 */
@DisallowConcurrentExecution
public class QuartzJobFactory implements Job {
	
	private static final Logger logger = Logger.getLogger(QuartzJobFactory.class);
	
	
	
	private NewsService newsService;
	
	private EssenceNewService essenceService;
	
	private NoteService noteService;
	
	private EssenceAuthorService authorService;

	public void execute(JobExecutionContext context) throws JobExecutionException{
		// TODO Auto-generated method stub
		if(newsService == null){
			newsService = SpringContextUtil.getBean(NewsService.class);
		}
		if(noteService == null){
			noteService = SpringContextUtil.getBean(NoteService.class);
		}
		if(essenceService == null){
			essenceService = SpringContextUtil.getBean(EssenceNewService.class);
		}
		if(authorService == null){
			authorService = SpringContextUtil.getBean(EssenceAuthorService.class);
		}
		ScheduleJob scheduleJob = (ScheduleJob)context.getMergedJobDataMap().get("scheduleJob");
		if(scheduleJob.getJobId().equals("10001")){
			try{
				String[] modules = {"新闻","笔记","名师"};
				Workbook wb = null;
				WritableWorkbook book = null;
				String filepath = ("/home/nju/data.xls");
				book = MyExcelUtils.checkSheetExists(wb, book, filepath);
				Date now = new Date();
				String date = DateUtil.dateToStr(now, "MM-dd HH:mm");
				for(String module : modules){
					WritableSheet sheet = book.getSheet(module);
					if(sheet == null){
						sheet = book.createSheet(module, book.getSheets().length);
					}
					if(module.equals("新闻")){
						NewsExample ex = new NewsExample();
						List<News> lists = newsService.selectByExample(ex);
						for(int i = 1 ; i < lists.size() ; i++){
							News note = lists.get(i-1);
							String title = note.getTitle();
							Cell cell = MyExcelUtils.getCellByContent(sheet, 1, title);
							writeToExcel(sheet,cell,date,0,title,note.getBrowseCount());
						}

					}else if(module.equals("笔记")){
						NoteExample ex = new NoteExample();
						List<Note> lists = noteService.selectByExample(ex);
						for(int i = 1 ; i < lists.size() ; i++){
							Note note = lists.get(i-1);
							String title = note.getSubName()+"-"+note.getDescription()+"-"+note.getSuitable();
							Cell cell = MyExcelUtils.getCellByContent(sheet, 1, title);
							writeToExcel(sheet,cell,date,note.getSubNum(),title,note.getBrowseCount());
						}
					}else if(module.equals("名师")){
						EssenceNewExample ex = new EssenceNewExample();
						List<EssenceNew> lists = essenceService.selectByExample(ex);
						for(int i = 1 ; i < lists.size() ; i++){
							EssenceNew note = lists.get(i-1);
							String title = authorService.selectByPrimaryKey(note.getAuthor()).getName()+"-"+note.getTitle();
							Cell cell = MyExcelUtils.getCellByContent(sheet, 1, title);
							writeToExcel(sheet,cell,date,note.getSubType(),title,note.getBrowseTimes());
						}
					}
				}
				book.write();
				book.close();
			}catch(Exception e){
				
			}
//			Date now = new Date();
//			UnreadExample urex = new UnreadExample();
//			Unread read = new Unread();
//			EssenceExample eex = new EssenceExample();
//			eex.createCriteria().andDateEqualTo(MyDateUtils.parseDateWithDay(now));
//			read.setEssence(essenceService.countByExample(eex));
//			read.setDate(MyDateUtils.parseDateWithDay(now));
//			unreadService.updateByExampleSelective(read, urex);
    	}
	}
	public void writeToExcel(WritableSheet sheet,Cell cell,String date,int subject,String title,int count)throws Exception{
		//说明这个已经有了
		if(cell != null){
			int columns = sheet.getColumns();
			if(!date.equals(sheet.getCell(columns-1, 0).getContents())){
				sheet.addCell(new Label(columns,0,date));
			}
			sheet.addCell(new Label(sheet.getColumns()-1,cell.getRow(),String.valueOf(count)));
		}else{
			if(StringUtils.isBlank(sheet.getCell(0, 0).getContents())){
				sheet.addCell(new Label(0,0,"科目"));
				sheet.addCell(new Label(1,0,"标题"));
			}
			if(!date.equals(sheet.getCell(sheet.getColumns()-1, 0).getContents())){
				sheet.addCell(new Label(sheet.getColumns(),0,date));
			}
			int rows = sheet.getRows();
			sheet.addCell(new Label(0,rows,SubjectUtils.getSubjectByType(subject)));
			sheet.addCell(new Label(1,rows,title));
			sheet.addCell(new Label(sheet.getColumns()-1,rows,String.valueOf(count)));
		}
	}
	
	
}